package com.dingdang.sms.allinone.sender.impl

import com.dingdang.sms.allinone.config.AllInOneConfigurationProperties
import com.dingdang.sms.allinone.sender.AllInOneSender
import com.dingdang.sms.allinone.sender.ResultWrapper
import com.dingdang.sms.allinone.sender.Target
import com.qiniu.sms.SmsManager
import com.qiniu.util.Auth
import java.lang.RuntimeException

class QiniuSender(val properties: AllInOneConfigurationProperties) : AllInOneSender {

    val manager by lazy { SmsManager(Auth.create(properties.qiniuCloud?.appKey, properties.qiniuCloud?.appSecret)) }

    override fun send(target: Target, block: (ResultWrapper) -> Unit) {
        val result = send(target)
        block(result)
    }

    override fun send(target: Target): ResultWrapper {
        target.checkTemplateId()
        return if (target.isSingleTarget()) {
            sendSingle(target)
        } else {
            sendMulti(target)
        }
    }

    private fun sendMulti(target: Target): ResultWrapper {
        val resp = manager.sendMessage(target.templateId, target.mobileList?.toTypedArray(), target.params)
        return if (resp.isOK) {
            ResultWrapper().ok(resp.error, resp.bodyString())
        } else {
            ResultWrapper().error(resp.error, resp.statusCode, resp.bodyString())
        }
    }

    private fun sendSingle(target: Target): ResultWrapper {
        val resp = manager.sendSingleMessage(target.templateId, target.mobileList?.first(), target.params)
        return if (resp.isOK) {
            ResultWrapper().ok(resp.error, resp.bodyString())
        } else {
            ResultWrapper().error(resp.error, resp.statusCode, resp.bodyString())
        }
    }

}